package com.mainaer.wjokhttp.comment;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;


/**
 * activity基础类
 */
public abstract class BaseAppCompatActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String EXTRA_DATA = "extra_data";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 1.init intent
        Bundle bundle = getIntent().getExtras();
        if (savedInstanceState != null) {
            bundle = savedInstanceState;
        }
        if (bundle != null) {
            getSavedData(bundle);
        }
        // 2. init layout id
        if (getLayoutId() != 0) {
            setContentView(getLayoutId());
        }
        // 3.init head view
        initHeadView();
        // 4.init view
        initView();
        // 5. init data
        initData();
    }

    /**
     * 初始化布局,建议所有子类重此方法
     *
     * @return layout id
     */
    public abstract
    @LayoutRes
    int getLayoutId();
    
    /**
     * 初始化headview组件,建议所有子类重此方法
     */
    public void initHeadView() {
        
    }
    
    /**
     * 初始化view组件,建议所有子类重此方法
     */
    public abstract void initView();
    
    /**
     * 获得onSaveInstanceState中保存的数据Bundle,局建议所有子类重此方法
     */
    public void getSavedData(Bundle bundle) {
        
    }
    
    /**
     * 初始化数据,建议所有子类重此方法
     */
    public void initData() {
        
    }
    
    protected void setOnclickListener(View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                view.setOnClickListener(this);
            }
        }
    }
    
    @Override
    public void onClick(View v) {
        
    }
    
    @SuppressWarnings("unchecked")
    protected <T extends View> T $(@IdRes int id) {
        return (T) findViewById(id);
    }
    
    @SuppressWarnings("unchecked")
    protected <T extends View> T $(View parent, @IdRes int id) {
        return (T) parent.findViewById(id);
    }

    /**
     * Activity中添加Fragment
     * 目前主要用在OA部分
     * 例如：showFragment(new NoticeFragment(),R.id.fl_anncs, false);
     *
     * @param fragment
     * @param frameId
     * @param addToBackStack
     */
    public void showFragment(Fragment fragment, int frameId, boolean addToBackStack) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(frameId, fragment);
        if (addToBackStack) {
            transaction.addToBackStack(null);
        }
        transaction.commit();
    }
}
